package com.yadong.smarthome2.udpbroadcast;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

import android.os.AsyncTask;
import android.text.TextUtils;
import android.util.Log;

public class BroadcastSenderTask extends AsyncTask<String, Void, Boolean>{
    private SendDoneListener mListener;

    public BroadcastSenderTask(SendDoneListener listener) {
        this.mListener = listener;
    }

    @Override
    protected Boolean doInBackground(String... params) {
        if (params.length != 2 || TextUtils.isEmpty(params[0]) || TextUtils.isEmpty(params[1])) {
            throw new IllegalArgumentException("params length must be 2");
        }
        DatagramSocket client = null;
        try {
            int port = Integer.parseInt(params[0]);
            byte[] msg = params[1].getBytes();
            InetAddress inetAddr = InetAddress.getByName("255.255.255.255");
            client = new DatagramSocket();
            DatagramPacket sendPack = new DatagramPacket(msg, msg.length, inetAddr,
                    port);
            client.send(sendPack);
            Log.d("BroadcastSenderTask", " Net broadcast send done on port:" + port);
            return true;
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("prot must be a number");
        } catch (SocketException e) {
            e.printStackTrace();
            return false;
        } catch (UnknownHostException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            if (client != null) {
                client.close();
            }
        }
    }

    @Override
    protected void onPostExecute(Boolean result) {
        if (mListener != null)
            mListener.sendDone(result);
    }

    public interface SendDoneListener{
        public void sendDone(boolean success);
    }

}
